//
//  MHGameDetailViewController.m
//  MHO
//
//  Created by papo on 2/24/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHGameDetailViewController.h"
#import "MHNavibarView.h"
#import "Application.h"
#import "UIImageView+WebCache.h"
#import "Lib.h"
#import "Contants.h"
#import "MHCommentCell.h"
//#import <FacebookSDK/FacebookSDK.h>
#import "DownloadManager.h"
#import "MHRateView.h"
#import "MHAppDelegate.h"
#import "CollectionCell.h"
#import "Collection.h"
#import "AFPickerView.h"
#import "MHDownloadViewController.h"
#import "MHCollectionCell.h"
#import "MHGameCell.h"

@interface MHGameDetailViewController ()
{
    MHNavibarView* navibarView;
    UITextView* _detailGameTextView;
    __weak IBOutlet UILabel *lbSizeOfApp;
    __weak IBOutlet UILabel *lbVersionOfApp;
    __weak IBOutlet UILabel *lbVerionOfApp2;
    __weak IBOutlet UILabel *lbDownloadCount;
    IBOutlet UITableView *commentTable;
    IBOutlet UIView *reviewHeader;
    __weak IBOutlet UILabel *lbVoteCount;
    __weak IBOutlet UITextField *textfieldComment;
    IBOutlet UIView *commentView;
    IBOutlet UIView *collectionHeader;
    IBOutlet UITableView *collectionTable;
    UIView*         _wrapCollectView;

    MHRateView* _rateView;
    NSInteger     _usersRateCount;
    
    int             _relateCurrentPage;
}
@property (weak, nonatomic) IBOutlet UITableView *mTableView;
@property (strong, nonatomic) IBOutlet UIView *topView;
@property (strong, nonatomic) IBOutlet UIView *buttonView;
@property (weak, nonatomic) IBOutlet UILabel *appName;
@property (weak, nonatomic) IBOutlet UIImageView *appImage;
@property (weak, nonatomic) IBOutlet UILabel *appSize;
@property (weak, nonatomic) IBOutlet UILabel *appDownload;
@property (weak, nonatomic) IBOutlet UIButton *detailButton;
@property (weak, nonatomic) IBOutlet UIButton *rateCommentButton;
@property (weak, nonatomic) IBOutlet UIButton *collectionButton;
@property (weak, nonatomic) IBOutlet UIButton *lienQuanButton;

@property (nonatomic, strong) NSArray* collectionList;
@property (nonatomic, strong) NSArray* farvoriteList;
@property (nonatomic, strong) NSArray* relateAppsList;
@property (nonatomic, strong) NSMutableArray*  collectionGameList;

@property (nonatomic, weak) IBOutlet UIView* createCollectionView;
@property (nonatomic, weak) IBOutlet UITextField* collectionTitleTextField;
@property (nonatomic, weak) IBOutlet UITextView* collectionDescriptionTextView;

@end

@implementation MHGameDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    navibarView = [MHNavibarView createWithTitle:@"Game" leftButton:nil rightButton:nil searchButton:YES];
    [navibarView setActionSelectorDelegate:self left:@selector(leftButtonPressed:) right:nil search:nil];
    [navibarView setRootViewController:self];
    [self.view addSubview:navibarView];

    // rate view
    _rateView = [MHRateView rateViewFromNib];
    [_rateView setFrame:CGRectMake(8, 80, 80, 20)];
    [_rateView setContentScaleFactor:0.5];
    [self.topView addSubview:_rateView];
    
    self.detailTableView.backgroundColor = [UIColor clearColor];
    self.detailTableView.hidden = NO;

//    [self updateAppInfo];

    [self registerForKeyboardNotifications];

    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView:)];
    [tap setDelegate:self];
    [tap setCancelsTouchesInView:NO];
    [self.view addGestureRecognizer:tap];
    
    [collectionTable registerNib:[UINib nibWithNibName:@"MHCollectionCell" bundle:nil] forCellReuseIdentifier:@"CollectionCell"];
    
    
    _wrapCollectView = [[UIView alloc] initWithFrame:self.view.frame];
    _wrapCollectView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.4];
    [self.view addSubview:_wrapCollectView];
    
    
    self.createCollectionView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 3);
    self.createCollectionView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.createCollectionView.layer.borderWidth = 1;
    self.createCollectionView.layer.cornerRadius = 10;
    self.createCollectionView.backgroundColor = [UIColor lightGrayColor];
    self.createCollectionView.layer.masksToBounds = YES;
    [_wrapCollectView addSubview:self.createCollectionView];
    _wrapCollectView.hidden = YES;
    
    _collectionDescriptionTextView.layer.borderWidth = 1;
    _collectionDescriptionTextView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _collectionDescriptionTextView.layer.cornerRadius = 10;
    _collectionDescriptionTextView.layer.masksToBounds = YES;
    self.mTableView.scrollEnabled = NO;
    
    
    [self performSelector:@selector(firstLoad) withObject:Nil afterDelay:0.3f];
}

- (void)firstLoad {
    [self showTableView:1];
}

- (void)viewDidAppear:(BOOL)animated {
    [self reloadData];
    [self updateAppInfo];
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//- (void)setApp:(Application *)app {
//    Application* nApp = [[Application alloc] init];
//}

- (void)updateAppInfo{
    [Application updateViewCountForId:self.app.appId];
    lbDownloadCount.text = [NSString stringWithFormat:@"%ld", (long)self.app.totalDownload];
    lbSizeOfApp.text = self.app.size;
    lbVerionOfApp2.text = self.app.versionApp;
    lbVoteCount.text = [NSString stringWithFormat:@"(%ld)", (long)self.app.totalVote];

    [_rateView setRateInt:self.app.rate];

    self.appId = self.app.appId.integerValue;
}

- (void)reloadData {
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        Application* app = [Application appDetail];
//        self.app.rate = app.rate;
//        self.app.totalPoint = app.totalPoint;
//        self.app.totalDownload = app.totalDownload;
        
        if (!collectionTable.hidden && [Lib isUserLogin]) {
            NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/chude?IdSystem=2&User=%@&pageIndex=0&pageSize=20&key=%@", [Lib stringForKey:@"Email"], kServerKey];
            _collectionList = [Collection getCollectionFromUrl:url];
            NSString* colUrl = @"http://mobile.mho.vn/services/chude?gameid=0&chudeid=%@&pageIndex=0&pageSize=6&key=%@";
            
            if (self.collectionGameList == nil) {
                self.collectionGameList = [NSMutableArray array];
            }
            else {
                [self.collectionGameList removeAllObjects];
            }
            
            for (Collection* col in _collectionList) {
                NSString* cUrl = [NSString stringWithFormat:colUrl, col.colletionId, kServerKey];
                NSArray* array = [Application appsFromServiceUrl:cUrl];
                if (array) {
                    [self.collectionGameList addObject:array];
                }
            }
        }
        else if (!self.lienquanTableView.hidden) {
            NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/Game?IdGame=%@&IdCategoryGame=0&IdSystem=2&IdGroup=1&isHot=0&isNews=0&isMostView=0&pageIndex=0&pageSize=10&key=%@", self.app.appId, kServerKey];
            _relateAppsList = [Application appsFromServiceUrl:url];
            self.tableView = self.lienquanTableView;
            _relateCurrentPage = 1;
        }
        
        // main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            if (!self.detailTableView.hidden) {
                [self.detailTableView reloadData];
                
            }
            else if (!commentTable.hidden) {
                [commentTable reloadData];
            }
            else if (self.lienquanTableView && !self.lienquanTableView.hidden){
                [self.lienquanTableView reloadData];
            }
            else if (!collectionTable.hidden){
                [collectionTable reloadData];
            }
            [self updateAppInfo];
            [self.mTableView reloadData];
            _downloadButton.enabled = true;
        });
    });
}

- (void)startLoading {
    [self stopLoading];
}

- (void)refresh {
    
}

- (void)loadingMore {
    if (!self.lienquanTableView.hidden) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/Game?IdGame=%@&IdCategoryGame=0&IdSystem=2&IdGroup=1&isHot=0&isNews=0&isMostView=0&pageIndex=%d&pageSize=10&key=%@", self.app.appId, _relateCurrentPage, kServerKey];
            NSArray* array = [Application appsFromServiceUrl:url];
            if (array &&array.count > 0) {
                _relateAppsList = [_relateAppsList arrayByAddingObjectsFromArray:array];
                ++_relateCurrentPage;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.lienquanTableView reloadData];
                [self stopLoadingMore];
            });
        });
        
    }
}

#pragma mark UIGestureRecognizerDelegate methods

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    
    if ((_wrapCollectView.hidden && [touch.view isDescendantOfView:collectionTable])) {
        
        // Don't let selections of auto-complete entries fire the
        // gesture recognizer
        return NO;
    }
    
    return YES;
}


- (void)tapView:(UIGestureRecognizer*)tap {
    [self.view endEditing:YES];
    
    if ([_collectionTitleTextField isFirstResponder]) {
        [_collectionTitleTextField resignFirstResponder];
    }
    else if ([_collectionDescriptionTextView isFirstResponder]) {
        [_collectionDescriptionTextView resignFirstResponder];
    }
    else if (_wrapCollectView.hidden == NO) {
        _wrapCollectView.hidden = YES;
    }
    
//    if (_collectionPicker && tap.view != _collectionPicker) {
//        [UIView animateWithDuration:0.2 animations:^{
//            CGRect frame = _collectionPicker.frame;
//            frame.origin.y = [UIScreen mainScreen].bounds.size.height;
//            _collectionPicker.frame = frame;
//            
//        } completion:^(BOOL finished) {
//            [_collectionPicker removeFromSuperview];
//            _collectionPicker = nil;
//        }];
//    }
}

#pragma mark - manage keyboard event
- (void)registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWasShown:)
                                                 name:UIKeyboardDidShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillBeHidden:)
                                                 name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"MHCollectionCellDelete" object:nil];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)receiveNotification:(NSNotification*)aNotification {
    [self reloadData];
}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect rect = commentView.frame;
    rect.origin.y -= (kbSize.height - 46);
    commentView.frame = rect;
    
    if (_wrapCollectView.hidden == NO) {
        CGRect frame = self.createCollectionView.frame;
        float offset = frame.origin.y + frame.size.height + kbSize.height - self.view.frame.size.height - 46;
        if (offset > 0) {
            frame.origin.y -= (offset);
            [UIView animateWithDuration:0.3 animations:^{
                self.createCollectionView.frame = frame;
            }];
        }
//        [self.tableView setUserInteractionEnabled:NO];
    }
}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGRect rect = commentView.frame;
    rect.origin.y += (kbSize.height - 46);
    commentView.frame = rect;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.createCollectionView.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 3);
    }];
//    [self.tableView setUserInteractionEnabled:YES];
}

#pragma mark - uitextfield delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
//    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - TableView source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.mTableView) {
        return 2;
    }
    else if (tableView == self.detailTableView) {
        return 1;
    }
    else if (tableView == commentTable ) {
        return 1;
    }
    else if (tableView == collectionTable) {
        return 1;
    }
    
    // default
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.mTableView == tableView) {
        if (section == 0) {
            return 1;
        }
        return 1;
    }
    else if (self.detailTableView == tableView ) {
        return 2;
    }
    else if (tableView == commentTable ) {
        return 1;
    }
    else if (tableView == collectionTable) {
        if (!_collectionList) {
            return 1;
        }
        return 1 + _collectionList.count;
    }
    else if ( tableView == self.lienquanTableView) {
        return _relateAppsList.count;
    }
    
    // default
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    CGFloat tbHeight = self.mTableView.frame.size.height - 110 - self.buttonView.frame.size.height;
    
    // MARK: main table view
    if (self.mTableView == tableView) {
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }

        if (indexPath.section == 0) {
            [self.topView removeFromSuperview];
            [cell.contentView addSubview:self.topView];
        }
        else if (indexPath.section == 1) {
            [self.detailTableView removeFromSuperview];
            [cell.contentView addSubview:self.detailTableView];
            [commentTable removeFromSuperview];
            [cell.contentView addSubview:commentTable];
            [collectionTable removeFromSuperview];
            [cell.contentView addSubview:collectionTable];
            [self.lienquanTableView removeFromSuperview];
            [cell.contentView addSubview:self.lienquanTableView];
        }

        if (self.app) {
            self.appName.text = self.app.appName;
            [self.appImage setImageWithURL:[Contants getImageUrl:_app.imagePath width:70 height:70]];
            
        }
    }
    // MARK Detail Table view
    else if (self.detailTableView == tableView) {
        if (cell == nil) {
            cell = [[UITableViewCell alloc] init];
            
            if (indexPath.row == 0) {
                [self.pictureAlbum setFrame:CGRectMake(0, -210, 320, 250)];
                [cell.contentView addSubview:self.pictureAlbum];
                for (int i = 0; i < self.app.pictureAlbumUrls.count; i++) {
                    UIImageView* img = [[UIImageView alloc] initWithFrame:CGRectMake(0 + i * 320, 0, 320, 250)];
                    [img setContentMode:UIViewContentModeScaleAspectFit];
                    [img setTag:i + 1];
                    [self.pictureAlbum addSubview:img];
                }
            }
            else if (indexPath.row == 1) {
                UITextView* label = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
                [label setTag:12];
                [label setEditable:NO];
                [label setDataDetectorTypes:UIDataDetectorTypeAll];
                [cell.contentView addSubview:label];
                [label setScrollEnabled:NO];
                _detailGameTextView = label;
            }
            [self.pictureAlbum setContentSize:CGSizeMake(320 * (self.app.pictureAlbumUrls.count - 1), 250)];
        }
        
        if (indexPath.row == 0) {
            for (int i = 0; i < self.app.pictureAlbumUrls.count; i++) {
                UIImageView* img = (UIImageView*)[self.pictureAlbum viewWithTag:i + 1];
                if (img) {
                    [img setImageWithURL:self.app.pictureAlbumUrls[i]];
                }
            }
        }
        else if (indexPath.row == 1) {
            UITextView* label = (UITextView* )[cell.contentView viewWithTag:12];
            if (label) {
                [label setText:self.app.detail];
                CGRect frame = label.frame;
                CGSize size = [Lib text:self.app.detail sizeWithFont:label.font constrainedToSize:CGSizeMake(320, 9000)];
                frame.size.height = size.height + 50;
                [label setFrame:frame];
            }
        }
        CGRect frame = self.detailTableView.frame;
        frame.size.height = tbHeight;
        self.detailTableView.frame = frame;
    }
    // MARK: comment table view
    else if (tableView == commentTable) {
        if (indexPath.row == 0) {
            if (!cell) {
                cell = [[UITableViewCell alloc] init];
            }
            
        }
        else {
            if (!cell) {
                MHCommentCell* cmCell = [MHCommentCell cellFromNib];
                
                cell = cmCell;
            }
        }
        
        CGRect frame = commentTable.frame;
        frame.size.height = tbHeight;
        commentTable.frame = frame;
    }
    // MARK: collection table
    else if (tableView == collectionTable) {
//        if (indexPath.section == 0) {
//            if (!cell) {
//                cell = [[UITableViewCell alloc] init];
//            }
//            [collectionHeader removeFromSuperview];
//            [cell.contentView addSubview:collectionHeader];
//        }
//        else
        if (indexPath.row < _collectionList.count){
            MHCollectionCell* mCell = [tableView dequeueReusableCellWithIdentifier:@"CollectionCell"];
            if (!mCell) {
                mCell = [[[NSBundle mainBundle] loadNibNamed:@"MHCollectionCell" owner:self options:nil] objectAtIndex:0 ];
            }
            Collection* app = (Collection*)_collectionList[indexPath.row];
            [mCell setCollection:app];
            
            if (indexPath.row < _collectionGameList.count) {
                NSArray* array = [self.collectionGameList objectAtIndex:indexPath.row];
                [mCell setListGame:array];
            }
            
            cell = mCell;
            [mCell setNeedsDisplay];
        }
        else {
            if (!cell) {
                cell = [[UITableViewCell alloc] init];
                UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
//                button.backgroundColor = [UIColor redColor];
                [button setImage:[UIImage imageNamed:@"btn_tao_chu_de.png"] forState:0];
                [button setFrame:CGRectMake(85, 30, 150, 38)];
                [button addTarget:self action:@selector(showCreateCollectionView:) forControlEvents:UIControlEventTouchUpInside];
                [button setTag:123];
                [cell.contentView addSubview:button];
                
            }
            cell.contentView.backgroundColor = [UIColor clearColor];
            
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            UIButton* button = (UIButton*)[cell.contentView viewWithTag:123];
            if (button) {
                [cell.contentView bringSubviewToFront:button];
                [button setNeedsDisplay];
            }
            [cell.contentView sendSubviewToBack:cell.textLabel];
        }
        
        CGRect frame = collectionTable.frame;
        frame.size.height = tbHeight;
        collectionTable.frame = frame;
    }
    else if (tableView == self.lienquanTableView) {
        MHGameCell* mCell = (MHGameCell*)cell;
        if (!mCell) {
            mCell = [MHGameCell cellFromNib];
            cell = mCell;
        }
        
        Application* app = (Application*)[_relateAppsList objectAtIndex:indexPath.row];
        [mCell setApp:app];
        CGRect frame = self.lienquanTableView.frame;
        frame.size.height = tbHeight;
        self.lienquanTableView.frame = frame;
    }
    
    return cell;
}

- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView* view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"View"];
    if (!view) {
        if (tableView == self.mTableView) {
            view = self.buttonView;
        }
        else if (tableView == self.detailTableView ) {
            view = [[UIView alloc] init];
        }
        else if (tableView == commentTable) {
            view = reviewHeader;
        }
        else if (tableView == collectionTable) {
            view = collectionHeader;
        }
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.mTableView) {
        if (section == 1) {
            return self.buttonView.frame.size.height;
        }
    }
    
    else if (tableView == commentTable) {
        if (section == 0) {
            return commentView.frame.size.height;
        }
    }
    else if (tableView == collectionTable) {
        if (section == 0) {
            return collectionHeader.frame.size.height;
        }
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.mTableView == tableView) {
        if (indexPath.section == 0) {
            return 110;
        }

//        if (!self.detailTableView.hidden) {
//            return self.detailTableView.contentSize.height;
//        }
//        else if (!commentTable.hidden) {
//            NSLog(@"comment table height: %f", commentTable.contentSize.height);
//            return commentTable.contentSize.height;
//        }
//        else if (!collectionTable.hidden) {
//            return collectionTable.contentSize.height;
//        }
        return self.mTableView.frame.size.height - 110 - self.buttonView.frame.size.height;
    }
    else if (self.detailTableView == tableView) {
        if (indexPath.row == 0) {
            return 260;
        }
        else if (indexPath.row == 1) {
            CGSize height = [Lib text:self.app.detail sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(320, 9000)];
            return height.height + 50;
        }
    }
    else if (commentTable == tableView) {
//        if (indexPath.row == 0) {
//            return reviewHeader.frame.size.height;
//        }
        return 90;
    }
    else if (collectionTable == tableView ) {
//        if (indexPath.section == 0) {
//            return collectionHeader.frame.size.height;
//        }
        return 98;
    }
    else if (self.lienquanTableView == tableView) {
        return 90;
    }
    
    // default
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.lienquanTableView == tableView) {
        Application* app = (Application*)[_relateAppsList objectAtIndex:indexPath.row];
        if (app) {
            MHGameDetailViewController* vc = [[MHGameDetailViewController alloc] initWithNibName:@"MHGameDetailViewController" bundle:nil];
            vc.app = app;
            vc.appId = app.appId.intValue;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}



- (void)leftButtonPressed:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)reviewAction:(id)sender {
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL result = NO;
        result = [Application sendRate:[NSString stringWithFormat:@"%ld", (long)self.appId] rate:_usersRateCount];
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            if (result) {
                [self reloadData];
            }
            else {
              
            }
        });
    });
}
- (IBAction)rateAction:(UIButton *)sender {
    if (![Lib isUserLogin]) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn cần đăng nhập để thực hiện chức năng này!" cancelButtonTitle:@"Có" otherButtonTitles:@[@"Không"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {
                [[MHAppDelegate sharedApp].viewController showLoginVc];
            }
        }];
    }
    
    NSInteger tag = sender.tag;
    for (int i = 1; i <= 5; i++) {
        UIButton* button = (UIButton*)[reviewHeader viewWithTag:i];
        if (button) {
            if (i <= tag) {
                [button setImage:[UIImage imageNamed:@"star_yellow.png"] forState:UIControlStateNormal];
            }
            else{
                [button setImage:[UIImage imageNamed:@"star_gray.png"] forState:UIControlStateNormal];
            }
        }
    }
    NSInteger rate = tag;
    _usersRateCount = rate;
}
- (IBAction)commentAction:(id)sender {
}


- (IBAction)detailAction:(id)sender {
//    [self.detailTableView reloadData];
    [self showTableView:1];
}
- (IBAction)reviewAndCommentAction:(id)sender {
//    [commentTable reloadData];
    [self showTableView:2];
}
- (IBAction)collectionAction:(id)sender {
//    [collectionTable reloadData];
    [self showTableView:3];
}
- (IBAction)relateAction:(id)sender {
    [self showTableView:4];
//    self.lienquanTableView
}

- (void)showTableView :(NSInteger)index {
    // detail
    self.detailTableView.hidden = index != 1;
    self.detailButton.selected = index == 1;
    // review
    commentTable.hidden = index != 2;
    commentView.hidden = commentTable.hidden;
    self.rateCommentButton.selected = index == 2;
    // collection
    collectionTable.hidden = index != 3;
    collectionHeader.hidden = collectionTable.hidden;
    self.collectionButton.selected = index == 3;

    // relate
    self.lienquanTableView.hidden = index != 4;
    self.lienQuanButton.selected = index == 4;
     NSLog(@"111lienquan tb: %d", _lienquanTableView.hidden);
    [self reloadData];
}

#pragma mark - header Detail game
- (IBAction)shareFacebook:(id)sender {
    [Lib shareFacebook:self.app.logoPath];
}


- (IBAction)downloadGame:(id)sender {
    if ([DownloadManager startDownload:self.app]) {
        [self.downloadButton setEnabled:NO];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/gameex?type=incdownload&g=%@&key=%@", self.app.appId, kServerKey];
            NSLog(@"download url update: %@", url);
            [ServiceLib sendGetRequest:url];
            dispatch_async(dispatch_get_main_queue(), ^{
//                [self reloadData];
                MHDownloadViewController* vc = [[MHDownloadViewController alloc] initWithNibName:@"MHDownloadViewController" bundle:nil];
                [self.navigationController pushViewController:vc animated:YES];
            });
        });
    }
}
- (IBAction)addToCollection:(id)sender {
    if (![Lib isUserLogin]) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn phải đăng nhập để sử dụng chức năng này!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
        }];
        return;
    }
    
    NSIndexPath* indexPath = [collectionTable indexPathForSelectedRow];
    if (!indexPath) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn chưa chọn chủ đề!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
        }];
        return;
    }
    else {
        Collection* col = [self.collectionList objectAtIndex:indexPath.row];
        
        
        NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/ChuDe?Type=1&GameId=%@&ChuDeId=%@&key=%@", self.app.appId, col.colletionId, kServerKey];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* ret = [ServiceLib sendGetRequest:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                [Lib removeLoadingView];
                if (ret) {
                    [self reloadData];
                    [UIAlertView showWithTitle:@"Thông báo" message:[NSString stringWithFormat:@"Thêm ứng dụng vào %@ thành công!", col.collectionName] cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                        
                    }];
                }
            });
        });
    }
//    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/chude?IdSystem=1&User=%@&pageIndex=0&pageSize=100&key=%@", [Lib stringForKey:@"Email"], kServerKey];
//    [Lib showLoadingView];
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        _collectionList = [Collection getCollectionFromUrl:url];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [Lib removeLoadingView];
////            if (!_actionSheet) {
//                _actionSheet = [[UIActionSheet alloc] initWithTitle:@"Chọn bộ sưu tập" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"OK" otherButtonTitles:@"Huỷ", @"2", @"3", @"4",@"5", nil];
//            CGRect frame = [UIScreen mainScreen].bounds;
////            frame.origin.y = 100;
////            frame.size.height -= 100;
//            _actionSheet.bounds = frame;
//            _actionSheet.delegate = self;
//    
//                _collectionPicker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 150, [UIScreen mainScreen].bounds.size.width, 250)];
//                [_collectionPicker setDelegate:self];
//                [_collectionPicker setDataSource:self];
//            _collectionPicker.backgroundColor = [UIColor lightGrayColor];
//                [_actionSheet addSubview:_collectionPicker];
//                
////            }
//            [_collectionPicker selectRow:0 inComponent:0 animated:NO];
//            [_collectionPicker setShowsSelectionIndicator:YES];
//            [_collectionPicker reloadAllComponents];
//            [_actionSheet showInView:self.view];
//            
//        });
//    });
}

- (IBAction)addToFavorite:(id)sender {
    if (![Lib isUserLogin]) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn phải đăng nhập để sử dụng chức năng này!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
        }];
        return;
    }
    NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/LikeGame?Type=1&IdSystem=2&GameId=%@&User=%@&key=%@", self.app.appId, [Lib stringForKey:@"Email"], kServerKey];
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* ret = [ServiceLib sendGetRequest:url];
        dispatch_async(dispatch_get_main_queue(), ^{
            [Lib removeLoadingView];
            if (ret) {
                [UIAlertView showWithTitle:@"Thông báo" message:@"Thêm ứng dụng vào Yêu thích thành công!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                    
                }];
            }
        });
    });
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return self.collectionList.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    Collection* col = [self.collectionList objectAtIndex:row];
    return col.collectionName;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
//    [UIView animateWithDuration:0.2 animations:^{
//        CGRect frame = _collectionPicker.frame;
//        frame.origin.y = [UIScreen mainScreen].bounds.size.height;
//        _collectionPicker.frame = frame;
//        
//    } completion:^(BOOL finished) {
//        [_collectionPicker removeFromSuperview];
//        _collectionPicker = nil;
//    }];
//    if (row >= _collectionList.count) {
//        return;
//    }
    
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        Collection* col = [self.collectionList objectAtIndex:[_collectionPicker selectedRowInComponent:0]];
        
        if (col.colletionId.integerValue == 0) {
            [self addToFavorite:nil];
            return;
        }
        NSString* url = [NSString stringWithFormat:@"http://mobile.mho.vn/services/ChuDe?Type=1&GameId=%@&ChuDeId=%@&key=%@", self.app.appId, col.colletionId, kServerKey];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSString* ret = [ServiceLib sendGetRequest:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                [Lib removeLoadingView];
                if (ret) {
                    [UIAlertView showWithTitle:@"Thông báo" message:[NSString stringWithFormat:@"Thêm ứng dụng vào %@ thành công!", col.collectionName] cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                        
                    }];
                }
            });
        });
    }
    
}

- (void)showCreateCollectionView:(id)sender {
    _wrapCollectView.hidden = NO;
}

- (IBAction)comfirmCreateCollection:(id)sender {
    NSString* name = _collectionTitleTextField.text;
    NSString* des = _collectionDescriptionTextView.text;
    if (!name || name.length == 0) {
        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn chưa nhập tên chủ đề!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
            
        }];
        return;
    }
    
    //    if (!des || des.length == 0) {
    //        [UIAlertView showWithTitle:@"Thông báo" message:@"Bạn chưa nhập trích dẫn!" cancelButtonTitle:@"OK" otherButtonTitles:nil tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
    //
    //        }];
    //        return;
    //    }
    
    Collection* col = [[Collection alloc] init];
    col.collectionName = name;
    col.colletionId = @(0);
    col._description = des;
    col.userEmail = [Lib stringForKey:@"Email"];
    
    
    [Lib showLoadingView];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [Collection createNewCollection:col];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self reloadData];
            [Lib removeLoadingView];
            _wrapCollectView.hidden = YES;
            [self.createCollectionView endEditing: YES];
        });
    });
}
@end
